package com.huawei.classroom.student.h16;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer extends Thread{
	private int port;
	public void startListen(int port) {
		this.port = port;
		start();
	}
	@Override
	public void run() {
		try {
			ServerSocket server = new ServerSocket(this.port);
			System.out.println("server listen on port:" + this.port + " ok!");
			Socket socket = server.accept();
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			PrintWriter out = new java.io.PrintWriter(socket.getOutputStream());
			String line = in.readLine();
			while(!"bye".equals(line)) {
				out.write(line + "\r\n");
				out.flush();
				line = in.readLine();
			}
			//debug
			//System.out.println("ok server");
			server.close();
			socket.close();
			in.close();
			out.close();
		}catch(IOException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}
}
